import sys
import pygame
import threading
from constant import * 
from car import Car
from player import Player


'''初始化'''
pygame.init()  # 初始化
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))  # 设置主屏幕大小
map_image = pygame.image.load(MAP_IMAGE)  # 加载车辆
pygame.display.set_caption(GAME_NAME)  # 设置标题
clock = pygame.time.Clock()  # 创建时钟对象

'''移动的车辆'''
cars = {}  # 车辆字典，key:车辆名，value:车辆实例
car_group = pygame.sprite.Group()  # 创建车辆精灵组
for i in range(0, len(LINE_POINTS)):
    cars["car_" + str(i)] = Car()
    threading.Thread(target=cars["car_" + str(i)].run, args=(LINE_POINTS[i],)).start()
    car_group.add(cars["car_" + str(i)])  # 向车辆组内添加精灵

'''移动的玩家'''
player_1 = Player()
player_group = pygame.sprite.Group()  # 创建玩家精灵组
player_group.add(player_1)  # 向玩家组内添加精灵
pygame.key.set_repeat(player_1.delay, player_1.interval)  # 设置按键重复响应, 第一次响应延时delay(ms), 重复间隔interval(ms)


while True:
    clock.tick(60)  # 设置游戏的fps

    '''监听事件'''
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # 退出事件
            pygame.quit()  # 卸载所有模块
            sys.exit()  # 终止程序

        if event.type == pygame.KEYDOWN:  # 键盘事件
            player_1.goto(event)  # 玩家移动

    '''碰撞检测'''
    carsh_list = pygame.sprite.groupcollide(car_group, player_group, False, True)  # True: 碰撞后删除精灵

    '''填充屏幕'''
    screen.fill(SCREEN_COLOR)  # 填充屏幕颜色
    screen.blit(map_image, (0, 0))  # 绘制背景图到屏幕上

    for i in range(0, len(car_group)):  # 绘制车辆到屏幕上
        screen.blit(cars["car_" + str(i)].image,(cars["car_" + str(i)].rect.centerx, cars["car_" + str(i)].rect.centery),)

    for i in range(0, len(player_group)):
        screen.blit(player_1.image, (player_1.rect.centerx, player_1.rect.centery))  # 绘制玩家到屏幕上

    pygame.display.update()  # 刷新显示屏
